import { clamp } from 'cc';
import { SequenceTree } from './BTree/SequenceTree';
import { BNode } from './type/BNode';
import { IEvent } from './type/IEvent';
import { TaskState } from './type/TaskState';

// 行为树的根节点,默认为sequence序列
export class BehaviorTree extends BNode implements IEvent {
    public root: SequenceTree = new SequenceTree(); //入口节点

    addChild(...nodes: IEvent[]) {
        this.root.children.push(...nodes);
    }

    removeChild(node: IEvent) {
        const index = this.root.children.indexOf(node);
        if (index != -1) {
            this.root.children.splice(index, 1);
        }
    }

    // 开始
    run() {
        this.root.task.running();
        this.root.onStart(this.blackBoard);
        this.task.running();
    }

    //重置
    reset() {
        this.root.task.reset();
        this.root.onReset();
        this.root.children = [];
        this.task.reset();
    }

    //更新
    update(dt: number): void {
        if (this.task.getState() != TaskState.running) {
            return;
        }

        dt = clamp(dt, 0, 0.04);
        this.root.onUpdate(dt);
        if (this.root.task.getState() == TaskState.done) {
            this.task.done();
        }
    }

    isRunning() {
        return this.root.getState() == TaskState.running;
    }

    override onStart(blackboard?: any): void {
        //不使用
        blackboard;
    }
}
